<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { listUser } from '@/api/user'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

const router = useRouter()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  role: 'user' // 默认为用户登录
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 登录加载状态
const loading = ref(false)

// 表单引用
const loginFormRef = ref()

// 处理登录
const handleLogin = async () => {
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 调用用户登录API
        const result = await listUser({
          username: loginForm.username,
          password: loginForm.password
        })
        if (result && result.length > 0 && result[0].role == loginForm.role) {
          const user = result[0]
          
          // 检查用户状态
          if (user.status === 1) {
            ElMessage.error('账号已被冻结')
            return
          }

           // 存储用户信息到全局状态
           userStore.setUserInfo({
             id: user.id,
             role: user.role,
             username: user.username
           })

          ElMessage.success('登录成功')

          console.log(user.role)
          console.log(loginForm.role)
          
          // 根据角色跳转
          switch(user.role) {
            case 0: // 用户
              router.push('/user/home')
              break
            case 1: // 门店
              router.push('/store/dashboard')
              break
            case 2: // 管理员
              router.push('/admin/dashboard')
              break
            default:
              router.push('/user/home')
          }
        } else {
          ElMessage.error('用户名或密码错误')
        }
      } catch (error) {
        console.error('登录错误', error)
        ElMessage.error('登录失败，请稍后再试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">
        <h2>药店管理系统</h2>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="角色选择">
          <el-radio-group v-model="loginForm.role">
            <el-radio label="0">用户</el-radio>
            <el-radio label="1">门店</el-radio>
            <el-radio label="2">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码" 
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            @click="handleLogin" 
            class="login-button"
          >
            登录
          </el-button>
        </el-form-item>
        
        <div class="login-options">
          <el-button type="text" @click="goToRegister">没有账号？立即注册</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
}

.login-title h2 {
  font-size: 24px;
  color: #409EFF;
}

.login-button {
  width: 100%;
}

.login-options {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>